from django.shortcuts import render, HttpResponse, redirect
from rbac import models

from rbac.service.init_permission import init_permission


def login(request):
    """
    登录后要初始化权限信息
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'login.html')

    # 获取用户信息
    username = request.POST.get("username")
    password = request.POST.get("password")

    # 判断用户是否存在
    user_obj = models.UserInfo.objects.filter(username=username, password=password).first()
    if not user_obj:
        return render(request, 'login.html', {'msg': '用户名或密码错误'})

    # 初识化权限
    init_permission(user_obj, request)

    return redirect('/customer/list/')
